 

// host
 var host = "https://api.ihiho.net/"

// api path
 var ctrlControlPath = "interface/control/ctrlControl"


 var tool = require('rjTool.js')

//tool method
//
//
//
//

//获取设备宽高
function getSystemWHInfo(cb){

wx.getSystemInfo({
  success: function(res) {
    // console.log(res.model)
    // console.log(res.pixelRatio)
    console.log(res.windowWidth)
    console.log(res.windowHeight)
    // console.log(res.language)
    // console.log(res.version)
    // console.log(res.platform)

    cb(res.windowWidth,res.windowHeight)

  }
})
}


function mapCtrlArray(originArr,cb){
 // console.log(originArr)
  // originArr = ["num:17,state:1", "num:18,state:0","num:19,state:1",,"num:15,state:1",]
  var lastArr = []   
  originArr.map(function(value,index,array){
      

          mapCtrlString(value,function(isSuccess,obj){
             
              if (isSuccess) {
                lastArr.push(obj)

              }
        
          })
          
     })

   

 

   sortLastObjArray(lastArr,function(la){
     
     cb(la)  
   
   })

}

function sortLastObjArray(array,cb){
   var la = array.sort(tool.compare('num'))
   cb(la)

}


function mapCtrlString(value,cb){
  
  var array = value.split(",")


  var la = array.map(function(currentValue,index,array){
    
      var lastArr = currentValue.split(':')
      
      if (lastArr[0] == "num") {

        return {num:lastArr[1]}
      }

      if (lastArr[0] == "state") {
        return {state:lastArr[1]}
      }

      if (lastArr[0]== "colorTemperature") {
        return {colorTemperature:lastArr[1]}
      }

      

  })
   
 if (la.length>1) {
  
  var obj1 = la[0]
  var obj2 = la[1]
  for (var key in obj2) {
    if (obj2.hasOwnProperty(key)===true) {
      obj1[key]=obj2[key];
    }
  }

   cb(true,obj1)


 }else{

  cb(false,nil)
 }

  

}






function formatTime(date) {
  var year = date.getFullYear()
  var month = date.getMonth() + 1
  var day = date.getDate()

  var hour = date.getHours()
  var minute = date.getMinutes()
  var second = date.getSeconds()


  return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}

function formatNumber(n) {
  n = n.toString()
  return n[1] ? n : '0' + n
}

// 登录接口
function login(userName,password,oemCode,cb){

  wx.request({
  url:  host + 'system/control/userLogin',
  data: {
   "userName": userName ,
   "password": password ,
   "oemCode": oemCode 

  },
  method: 'POST', // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
  // header: {}, // 设置请求的 header
  success: function(res){
   //保存登录信息
     let msg = res.data.msg
     if (msg == "0000" || msg == "0") {
     saveloginSuccess(res.data)
     cb(true,null)

    }
    else{
      cb(false,res.data.msg)
      }   
  },
  fail: function(res) {
    // fail
    cb(false,null)
  }
  })
}

//存储登录object
function saveloginSuccess(e){
   const externalLoginKey = e.externalLoginKey //睿居令牌
   // const isSubuser = e.isSubuser   //是否是子账号
   // const ysAccessToken = e.ysAccessToken //萤石令牌

   //直接存储登录数据
   wx.setStorageSync('rjUser', e)
 }

// 所有设备
function findUserAllDevices(cb){

   wx.request({
    //必需
    url:  host + 'interface/control/findUserAllDevices',
    data: {
      
    },
    header: {
        'Content-Type': 'application/json',
        'externalLoginKey': getExternalLoginKey()
    },
    success: function(res){
   //保存登录信息
     let msg = res.data.msg
     if (msg == "0000" || msg == "0") {
    
     cb(true,null)

    }
    else{
      cb(false,res.data.msg)
      }   
   },
    fail: function(res) {
       cb(false,null)
    }
   })
 }

//获取萤石令牌
function getExternalLoginKey(){
  const user = wx.getStorageSync('rjUser')
  return user.externalLoginKey
}

// 常用设备
function queryAllDeviceOnDesktop(cb){

   wx.request({
    //必需
    url:  host + 'interface/control/queryAllDeviceOnDesktop',
    data: {
      
    },
    header: {
        'Content-Type': 'application/json',
        'externalLoginKey': getExternalLoginKey()
    },
    success: function(res){
  

     let msg = res.data.msg
     if (msg == "0000" || msg == "0") {
     
     parseDeviceData(res,function(e){

       cb(true,e.devList)
     }) 

     

    }
    else{
      cb(false,res.data.msg)
      }   
   },
    fail: function(res) {
       cb(false,null)
    }
   })
}


function  parseDeviceData(e,cb){
 
   let dataList = e.data.devList
  let list = []

   for (var i = 0; i < dataList.length; i++) {
     
     let model  = {} 
   if (dataList[i].newDeviceName == null || dataList[i].newDeviceName == "") {

      model["deviceName"] = dataList[i].oldDeviceName
    }else{
      model["deviceName"] = dataList[i].newDeviceName

    }

    if (dataList[i].onlineMode == "0") {
      model["online"] = "离线"
    }else{
      model["online"] = "在线"
    }
   

    model["deviceId"] = dataList[i].deviceId
    model["deviceTypeId"] = dataList[i].deviceTypeId
    model["gwId"] = dataList[i].gwId
    model["gwName"] = dataList[i].gwName
    model["onlineMode"] = dataList[i].onlineMode
    model["roomId"] = dataList[i].roomId
    model["state"] = dataList[i].state
    model["serialNo"] = dataList[i].serialNo
    model["venderId"] = dataList[i].venderId
    model["oldDeviceName"] = dataList[i].oldDeviceName
    model["newDeviceName"] = dataList[i].newDeviceName
     
     list.push(model)

   }
  e.devList = list
  cb(e)
}


//获得所有常用场景
function queryAllSceneOnDesktop(cb){

  wx.request({
    //必需
    url:  host + 'scene/control/queryAllSceneOnDesktop',
    data: {
      
    },
    header: {
        'Content-Type': 'application/json',
        'externalLoginKey': getExternalLoginKey()
    },
    success: function(res){
   
     let msg = res.data.msg
     if (msg == "0000" || msg == "0") {
      cb(true,res.data.scenes)

    }
    else{
      cb(false,res.data.msg)
      }   
  },
    fail: function(res) {
       cb(false,null)
    }
  })
}


/*设备控制ctrl*/
function  ctrlControl(deviceId,ctrl,cb){

    wx.request({
    url:  host + ctrlControlPath,
    data: {
      'deviceId':deviceId,
      'ctrl':ctrl
    },
    header: {
        'Content-Type': 'application/json',
        'externalLoginKey': getExternalLoginKey()
    },
    method: 'POST',
    success: function(res){
     let msg = res.data.msg
     if (msg == "0000" || msg == "0") {
    
     cb(true,null)

    }
    else{
      cb(false,res.data.msg)
      }   
   },
    fail: function(res) {
      console.log(res)
       cb(false,null)
    }
   })
  
}


function test(){

  wx.request({
    url: 'http://ltyx.bluekjg.com/app/index/getAreaData?agent_id=1',
    data: {
    },
    header: {
    },
    method: 'GET',
    success: function (res) {
      console.log('test')
      console.log(res) 
    },
    fail: function (res) {
      console.log(res)
      cb(false, null)
    }
  })

}

function test1() {

  wx.request({
    url: 'http://ltyx.bluekjg.com/app/index/getBannerData?agent_id=1&ad_type=1',
    data: {
    },
    header: {
    },
    method: 'GET',
    success: function (res) {
      console.log('test1')
      console.log(res) 
    },
    fail: function (res) {
      console.log(res)
      cb(false, null)
    }
  })

}




module.exports = {
  formatTime: formatTime,
  login: login, //登录
  findUserAllDevices: findUserAllDevices, //获取所有设备
  queryAllDeviceOnDesktop: queryAllDeviceOnDesktop,// 常用设备
  queryAllSceneOnDesktop: queryAllSceneOnDesktop,  //获得所有常用场景
  ctrlControl:ctrlControl,     //设备控制
  mapCtrlArray:mapCtrlArray,    //map设备
  getExternalLoginKey:getExternalLoginKey, //睿居令牌获取-》string
  getSystemWHInfo:getSystemWHInfo,   //获取设备宽高
  test,
  test1
}
